import { createRouter, createWebHashHistory } from 'vue-router'
import { useDefaultStore } from '@/store/index'

import NProgress from '@/utils/progress'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/home/index.vue')
    },
    {
      path: '/detail',
      name: 'detail',
      component: () => import('@/views/detail/index.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/test',
      name: 'test',
      component: () => import('@/views/test/index.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/notFound/index.vue')
    }
  ],
  // to, from, savedPosition
  scrollBehavior(to) {
    // console.log('scrollBehavior >>> ',to, from, savedPosition)
    if (to.name === 'detail') {
      return {
        el: '#target',
        top: 10
      }
    }
    return null
  }
})

router.beforeEach((from, to, next) => {
  NProgress.start()
  const defaultStore = useDefaultStore()
  if (from.name !== 'login' && !defaultStore.getToken) {
    next('login')
    return
  }
  if (from.name === 'login' && defaultStore.getToken) {
    next('/')
    return
  }
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
